﻿using System;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;

namespace Learning.ParticleCoreUI.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class SSEController : Controller
    {
        [HttpGet]
        public async Task<IActionResult> Index()
        {
            //组织HTTP响应头
            Response.Headers.Add("Connection", "keep-alive");
            Response.Headers.Add("Cache-Control", "no-cache");
            Response.Headers.Add("Content-Type", "text/event-stream");

            //发送自定义事件
            var message = BuildSSE(new { Content = "SSE开始发送消息", Time = DateTime.Now }, "SSE_Start");
            Response.Body.Write(message, 0, message.Length);

            //自定义事件
            message = BuildSSE(new { Content = $"测试自定义事件，当前时间为{DateTime.Now}" }, "eventName");
            await Response.Body.WriteAsync(message, 0, message.Length);

            //每隔10秒钟向客户端发送一条消息
            while (true)
            {
                message = BuildSSE(new { Content = $"当前时间为{DateTime.Now}" });
                await Response.Body.WriteAsync(message, 0, message.Length);
                await Response.Body.FlushAsync();
                Thread.Sleep(5000);
            }
        }

        private byte[] BuildSSE<TMessage>(TMessage message, string eventName = null, int retry = 30000)
        {
            var builder = new StringBuilder();
            builder.Append($"id:{Guid.NewGuid().ToString("N")}\n");
            if (!string.IsNullOrEmpty(eventName))
                builder.Append($"event:{eventName}\n");
            builder.Append($"retry:{retry}\n");
            builder.Append($"data:{JsonConvert.SerializeObject(message)}\n\n");
            return Encoding.UTF8.GetBytes(builder.ToString());
        }
    }
}